﻿using System.Threading;
using Iorz.DomainSearch.Utils.Tools;

namespace Iorz.DomainSearch.Utils.Provider
{
    public class GodaddyProvider : IProvider
    {
        private int mTryCount = 1;

        private string mLog = "Error_Godaddy.log";

        public string GetName()
        {
            return "GoDaddy";
        }

        public bool Search(string domain, out bool isAvail)
        {
            return CheckDomainAvail(domain, out isAvail);
        }

        private bool CheckDomainAvail(string domain, out bool isAvail)
        {
            isAvail = false;

            var response = HttpHelper.GetHtml(new HttpHelper.HttpRequest()
            {
                Method = HttpHelper.HttpMethod.GET,
                UserAgent = "Mozilla/5.0 (Linux; U; Android 4.4.4; Nexus 5 Build/KTU84P) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
                Url = GetUrl(domain)
            });

            if (response.Exception == null
                && !string.IsNullOrEmpty(response.Html)
                && response.Html.IndexOf("\"ExactMatchDomain\":") != -1)
            {
                if (response.Html.IndexOf("\"IsAvailable\":true") != -1)
                {
                    Tracker.Log("domain.log", domain);
                    isAvail = true;
                }

                return true;
            }

            if (response.Exception == null)
                Tracker.Log(mLog, response.Html);
            else
                Tracker.Log(mLog, response.Exception.Message);

            if (mTryCount <= 3)
            {
                mTryCount++;
                Thread.Sleep(3000);
                return CheckDomainAvail(domain, out isAvail);
            }

            return false;
        }

        private string GetUrl(string domain)
        {
            return $"https://sg.godaddy.com/zh/domainsapi/v1/search/exact?q={domain}&key=dlp_offer_com&pc=91720155&ptl=1";
        }
    }
}
